package com.xinqi.modules.sys.document.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.common.base.response.PageInfo;
import com.xinqi.common.base.response.Param;
import com.xinqi.common.mybatis.utils.Pages;
import com.xinqi.common.mybatis.utils.Queries;
import com.xinqi.modules.sys.dict.manager.DictDocumentManager;
import com.xinqi.modules.sys.document.convert.DocumentManagerConvert;
import com.xinqi.modules.sys.document.domain.DocumentManagerEntity;
import com.xinqi.modules.sys.document.dto.req.DocumentManagerCreateDTO;
import com.xinqi.modules.sys.document.dto.req.DocumentManagerDeleteDTO;
import com.xinqi.modules.sys.document.dto.req.DocumentManagerQueryDTO;
import com.xinqi.modules.sys.document.dto.req.DocumentManagerTreeDTO;
import com.xinqi.modules.sys.document.dto.req.DocumentManagerUpdateDTO;
import com.xinqi.modules.sys.document.dto.rsp.DocumentManagerResultDTO;
import com.xinqi.modules.sys.document.dto.rsp.DocumentManagerTreeResultDTO;
import com.xinqi.modules.sys.document.manager.DocumentManagerManager;
import com.xinqi.modules.sys.document.service.DocumentManagerService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 文档管理表服务层实现
 *
 * @author: gzy
 * @date: 2023/05/28
 */
@Validated
@Service("documentManagerService")
@RequiredArgsConstructor
public class DocumentManagerServiceImpl implements DocumentManagerService {
    private final DocumentManagerConvert documentManagerConvert;
    private final DocumentManagerManager documentManagerManager;

    private final DictDocumentManager dictDocumentManager;

    /**
     * 分页查询 文档管理表数据
     */
    @Override
    @DS("slaver")
    public PageInfo<DocumentManagerResultDTO> page(Param pageable, DocumentManagerQueryDTO query) {
        Page<DocumentManagerResultDTO> page = documentManagerManager.findByPage(Pages.page(pageable), query);
        return Pages.convert(page);
    }

    /**
     * 查询 文档管理表数据
     */
    @Override
    public List<DocumentManagerResultDTO> find(DocumentManagerQueryDTO query) {
        return documentManagerManager.list(wrapper(query)).stream()
            .map(documentManagerConvert::convert).collect(Collectors.toList());
    }

    private LambdaQueryWrapper<DocumentManagerEntity> wrapper(DocumentManagerQueryDTO query) {
        LambdaQueryWrapper<DocumentManagerEntity> wrapper = Queries.lambda();
        Queries.accept(query.getId(), v -> wrapper.eq(DocumentManagerEntity::getId, v));
        return wrapper;
    }

    /**
     * 根据id查询 文档管理表数据
     */
    @Override
    public DocumentManagerResultDTO findById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        return Optional.ofNullable(documentManagerManager.findById(id)).map(documentManagerConvert::convert).orElse(null);
    }

    /**
     * 新增 文档管理表数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insert(DocumentManagerCreateDTO dto) {
        DocumentManagerEntity entity = documentManagerConvert.create(dto);
        if (Objects.nonNull(entity.getParentId()) && !Objects.equals(entity.getParentId(), 0L)) {
            entity.setParentTitle(this.findById(entity.getParentId()).getTitle());
        } else {
            entity.setParentId(0L);
            entity.setParentTitle("无");
        }
        if (Objects.nonNull(entity.getDocumentClassifyCode())) {
            entity.setDocumentClassifyName(dictDocumentManager.selectDictNameByCode(entity.getDocumentClassifyCode()));
        }
        if (Objects.nonNull(entity.getDisplayClassifyCode())) {
            entity.setDisplayClassifyName(dictDocumentManager.selectDictNameByCode(entity.getDisplayClassifyCode()));
        }
        documentManagerManager.save(entity);
        return entity.getId();
    }

    /**
     * 根据id修改 文档管理表数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateById(DocumentManagerUpdateDTO dto) {
        Optional.ofNullable(documentManagerManager.getById(dto.getId()))
            .orElseThrow(() -> CommonErrors.BAD_REQUEST.asException("数据不存在"));
        DocumentManagerEntity entity = documentManagerConvert.update(dto);
        if (Objects.nonNull(entity.getParentId()) && !Objects.equals(entity.getParentId(), 0L)) {
            entity.setParentTitle(this.findById(entity.getParentId()).getTitle());
        } else {
            entity.setParentId(0L);
            entity.setParentTitle("无");
        }
        if (Objects.nonNull(entity.getDocumentClassifyCode())) {
            entity.setDocumentClassifyName(dictDocumentManager.selectDictNameByCode(entity.getDocumentClassifyCode()));
        }
        if (Objects.nonNull(entity.getDisplayClassifyCode())) {
            entity.setDisplayClassifyName(dictDocumentManager.selectDictNameByCode(entity.getDisplayClassifyCode()));
        }
        return documentManagerManager.updateById(entity);
    }

    /**
     * 根据id删除 文档管理表数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        return documentManagerManager.removeOutById(id);
    }

    /**
     * 根据id删除 文档管理表数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(DocumentManagerDeleteDTO dto) {
        return deleteById(dto.getId());
    }

    @Override
    public List<DocumentManagerResultDTO> findAllByParentId(Long parentId) {
        return documentManagerManager.findByParentId(parentId);
    }

    @Override
    public List<DocumentManagerTreeResultDTO> findTree(DocumentManagerTreeDTO dto) {
        return documentManagerManager.findTree(dto);
    }

    @Override
    public List<DocumentManagerResultDTO> findAll(DocumentManagerQueryDTO dto) {
        return documentManagerManager.findAll(dto);
    }

}
